package com.group.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group.activity.dao.AppletPaymentDao;
import com.group.activity.dao.ShopOrderDao;
import com.group.activity.entity.AppletPaymentEntity;
import com.group.activity.entity.ShopOrderEntity;
import com.group.activity.exception.StockNotEnougnException;
import com.group.activity.feign.AdminFeignService;
import com.group.activity.service.ShopOrderService;
import com.group.activity.vo.PayAsyncVo;
import com.group.common.to.SeckillOrderTo;
import com.group.common.utils.PageUtils;
import com.group.common.utils.Query;
import com.group.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service("shopOrderService")
public class ShopOrderServiceImpl extends ServiceImpl<ShopOrderDao, ShopOrderEntity> implements ShopOrderService {
    @Autowired
    RabbitTemplate rabbitTemplate;

    @SuppressWarnings("all")
    @Autowired
    AppletPaymentDao appletPaymentService;

    @Autowired
    AdminFeignService adminFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ShopOrderEntity> page = this.page(
                new Query<ShopOrderEntity>().getPage(params),
                new QueryWrapper<ShopOrderEntity>()
        );

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void saveSeckillOrder(SeckillOrderTo to) {
        ShopOrderEntity orderEntity = new ShopOrderEntity();
        BeanUtils.copyProperties(to, orderEntity);
        orderEntity.setOrderDate(new Date());
        orderEntity.setOrderStatus(0);
        boolean save = this.save(orderEntity);
        R r = adminFeignService.lockStock(to);
        if (r.getCode()==0){
            log.info("锁库存成功");
        }else {
            throw new StockNotEnougnException(17788, "库存不足");
        }
        if (save){
            //延时关闭订单--》1m
            rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", orderEntity, new CorrelationData(UUID.randomUUID().toString()));
            //延时解锁库存--》2m
            rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", to,new CorrelationData(UUID.randomUUID().toString()));
        }
    }

    @Override
    public void closeSeckillOrder(ShopOrderEntity entity) {
        //关闭订单
        ShopOrderEntity orderEntity = baseMapper.selectById(entity.getOrderId());
        if (orderEntity.getOrderStatus()==0){
            orderEntity.setOrderStatus(4);
            baseMapper.updateById(orderEntity);
            //解锁库存
            SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
            BeanUtils.copyProperties(entity, seckillOrderTo);
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other.#",seckillOrderTo,new CorrelationData(UUID.randomUUID().toString()));
        }
    }

    @Override
    public String notifyorder(PayAsyncVo payAsyncVo) {
        //修改订单状态
        //订单号
        String out_trade_no = payAsyncVo.getOut_trade_no();

        ShopOrderEntity order_number = baseMapper.selectOne(new QueryWrapper<ShopOrderEntity>().eq("order_sn", out_trade_no));

        order_number.setOrderStatus(3);
        baseMapper.updateById(order_number);

        //添加支付表
        AppletPaymentEntity appletPaymentEntity = new AppletPaymentEntity();
        appletPaymentEntity.setOrderSn(out_trade_no);
        appletPaymentEntity.setPayCreatetime(new Date());
        Date parse = null;
        try {
            parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(payAsyncVo.getGmt_payment());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        appletPaymentEntity.setPayTime(parse);
        appletPaymentEntity.setPayThirdId(payAsyncVo.getTrade_no());
        appletPaymentEntity.setPayStatus(1);
        appletPaymentEntity.setPayThirdMessage(payAsyncVo.getSubject());
        int insert = appletPaymentService.insert(appletPaymentEntity);
        return insert > 0 ? "success" : "fail";

    }

    @Override
    public R submitOrder(ShopOrderEntity shopOrderEntity) {
        String orderSn = shopOrderEntity.getOrderSn();
        if (orderSn==null){
            //验证失败
            return R.error(777,"该订单已提交过,请勿重复提交");
        }else {
            //下订单
            ShopOrderEntity shopOrderEntity1 = new ShopOrderEntity();
            shopOrderEntity1.setOrderPayPrice("10");
            shopOrderEntity1.setOrderDate(new Date());
            int i = baseMapper.insert(shopOrderEntity1);
            if (i>0){
                //将订单信息放入延时队列
                rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",shopOrderEntity1,new CorrelationData(UUID.randomUUID().toString()));
            }
            return R.ok("下订单成功");
        }
    }

    @Override
    public ShopOrderEntity getOrderInfoByOrderSn(String orderSn) {
        return baseMapper.selectOne(new QueryWrapper<ShopOrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public List<ShopOrderEntity> getOrderList() {
//        UserTo userTo = LoginUserInterceptor.userTo.get();
//        Integer userId = userTo.getUserId();
        return baseMapper.selectList(new QueryWrapper<ShopOrderEntity>().eq("order_buyers_id", 1));
    }

}